<template>
	<view style="display: flex;flex-direction: column;">
		<view class="list-info">
			<image :src="productInfo.cover" class="goods-item-img" mode="aspectFill"></image>
			<view style="display: flex;flex-direction: column;flex: 1;margin-right: 16rpx;margin-top: 16rpx;">
				<view class="goods-item-title">{{productInfo.title}}</view>
				<view style="display: flex;margin-top: 8rpx;font-size: 24rpx;">
					<text style="color: #666666;">高佣{{productInfo.kolCosRatio}}%</text>
					<text style="color: #666666;margin-left: 20rpx;flex: 1;">公开{{productInfo.cosRatio}}%</text>
					<text style="color: #999999;">月售 {{productInfo.sales}}</text>
				</view>
				<view style="display: flex;margin-top: 16rpx;font-size: 24rpx;">
					<text style="color: #666666;margin-top: 4rpx;">预估赚</text>
					<text style="color: #EE0A24;font-size: 24rpx;margin-left: 4rpx;margin-top: 4rpx;">¥</text>
					<text style="color: #EE0A24;flex: 1;font-size: 28rpx;">{{productInfo.kolCosFee}}</text>
					<text style="color: #999999;margin-top: 4rpx">售价：¥{{productInfo.price}}</text>
				</view>
				<view style="display: flex;margin-top: 14rpx;margin-bottom: 16rpx;">
					<view style="flex: 1;"></view>
					<!-- <text class="receive-material-btn">领取素材</text> -->
					<text class="copy-link-btn" @click="copyLinkUrl(productInfo.url)">复制链接</text>
				</view>
			</view>
		</view>
		<view style="display: flex;margin-left: 32rpx;">
			<view @click="clickMaterialTab(true)" :class="currentTab===0?'tab-left-view-native':'tab-left-view'">
				<text style="margin-left: 24rpx;" :class="currentTab===0?'tab-txt-native':'tab-txt-view'">原创材料</text>
			</view>
			<view @click="clickMaterialTab(false)" :class="currentTab===1?'tab-right-view-native':'tab-right-view'">
				<text :class="currentTab===1?'tab-txt-native':'tab-txt-view'">图文材料</text>
			</view>
		</view>
		<view :class="currentTab === 0?'content-group-native':'content-group-view'">
			<block v-if="currentTab === 0">
				<view style="display: flex;align-items: center;margin-top: 20rpx;">
					<scroll-view class="original-tab" scroll-x="true"  :scroll-left="scrollLeft" >
						<block v-for="(item,index) in tabOriginalData" :key="index" >
							<view class="original-tab-item" :class=" [currentOriginalTab==index ? 'original-tab-active' : 'none'] " 
								:data-current="index" @click="clickTab">
								{{item.name}}
							</view>
						</block>
					</scroll-view>
				</view>
				<mescroll-body ref="mescrollRef" @init="mescrollInit" :height="700" :up="upOption" :down="downOption" @up="upCallback">
					<view style="margin-left: 16rpx;margin-right: 16rpx;">
						<view v-for="(item, index) in originalList" :key="index" :id="index">
							<view style="width: 33%;float:left;" @click="onItemClick(item.url)">
								<view class="original-list-info">
									<view style="width: 100%;height: 202rpx;position: relative;">
										<image class="item-original-img" :src="item.cover"></image>
										<view class="item-original-smegma"></view>
										<text class="item-original-size">{{item.times}}</text>
										<text class="item-original-type">{{item.typeName}}</text>
										<image class="item-original-icon" src="../../static/material/icon_video.png"></image>
									</view>
									<view style="display: flex;">
										<text class="item-original-time">{{item.publishTime}}</text>
										<text v-if="item.isDownloaded" class="item-original-already">已下载</text>
										<text v-else class="item-original-download">下载</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</mescroll-body>
				<view style="height: 30rpx;"></view>
			</block>
			<block v-else> 
				<block v-if="videoTitles.length>0">
					<view class="content-title-view">视频标题</view>
					<block v-for="(item, index) in videoTitles" :key="index" :id="index">
						<view class="copy-group-view">
							<view class="title-txt">{{item.content}}</view>
							<view class="line-view"></view>
							<text class="copy-btn" @click="copyLinkUrl(item.content)">复制</text>
						</view>
					</block>
				</block>
				<block v-if="lines.length>0">
					<view class="content-title-view">口播台词</view>
					<block v-for="(item, index) in lines" :key="index" :id="index">
						<view class="copy-group-view">
							<view class="title-txt">{{item.content}}</view>
							<view class="line-view"></view>
							<text class="copy-btn" @click="copyLinkUrl(item.content)">复制</text>
						</view>
					</block>
				</block>
				<block v-if="elasticTitles.length>0">
					<view class="content-title-view">产品卖点</view>
					<block v-for="(item, index) in elasticTitles" :key="index" :id="index">
						<view class="copy-group-view">
							<view class="title-txt">{{item.content}}</view>
							<view class="line-view"></view>
							<text class="copy-btn" @click="copyLinkUrl(item.content)">复制</text>
						</view>
					</block>
				</block>
				<view style="height: 30rpx;"></view>
			</block>
		</view>
		<uniPopup ref="showAgainPop" type="center" style="z-index: 9991;position: fixed;top: --window-top;left: 0;">
			<view class="pop-group"> 
				<text class="pop-title">温馨提示</text>
				<text class="pop-content">请确认是否下载视频</text>
				<view style="display: flex;width: 100%;">
					<view class="pop-btn-cancel" @click="cancelClick()">取消</view>
					<view class="pop-btn-sure" @click="confirmClick()">下载</view>
				</view>
			</view>
		</uniPopup>
	</view>
</template>

<script>
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	import uniPopup from '@/components/uni-popup/uni-popup.vue';
	import configUrls from '@/common/config.js';
	export default {
		mixins: [MescrollMixin],
		components:{
			uniPopup
		},
		data() {
			return {
				materialId: '',
				currentTab: 0, 
				tabOriginalData: [
					{id:0,name:"全部",value:""}
				],
				currentOriginalTab: 0,
				scrollLeft: 0,
				windowWidth: 0,
				productInfo: {},
				upOption:{
					noMoreSize: 10, //默认5
					empty:{
						icon: '/static/mine/img_manage_empty.png',
						tip: '没有原创材料', // 提示
					},
					textNoMore: '~ 没有更多原创材料 ~'
				},
				downOption: {
					native: true,
				},
				chooseOriginalType: '',
				originalList: [],
				videoTitles: [],
				lines: [],
				elasticTitles: [],
				downloadUrl: "",
			}
		},
		onLoad(options) {
			wx.getSystemInfo({
				success: (res) => {	
					this.windowWidth = res.windowWidth;
				}
			});
			if (options.id) {
				this.materialId = options.id;
				this.getMaterialDetail();
				this.getOriginalClassification();
			}
		},
		methods: {
			upCallback(page) {
				let that = this;
				this.$Request.postJson(configUrls.getOriginalList, {
					id: that.materialId,
					page: page.num,
					limit: 10,
					type: that.chooseOriginalType,
				}).then(res => {
					if (res.code == "10000") {
						const respData = res.data.result.data;
						if (respData == null) {
							that.mescroll.endSuccess(0);
						    return;
						}
						that.mescroll.endSuccess(respData.length);
						if(page.num == 1) that.originalList = []; 
						that.originalList=that.originalList.concat(respData);
					} else {
						that.originalList = [];
						that.mescroll.endSuccess(0);
						that.mescroll.endErr();
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					}
				}); 
			},
			onPullDownRefresh: function() {
				this.mescroll.resetUpScroll();
				uni.stopPullDownRefresh();
			},
			onItemClick(url) {
				this.downloadUrl = url;
				this.$nextTick(() => {
				    this.$refs['showAgainPop'].open();
				})
			},
			confirmClick:function() {
				this.saveVideoClick(this.downloadUrl);
				this.$nextTick(() => {
				    this.$refs['showAgainPop'].close();
				})
			},
			cancelClick:function(){
				this.$nextTick(() => {
				    this.$refs['showAgainPop'].close();
				})
			},
			getMaterialDetail() {
				let that = this;
				this.$Request.postJsonLoadView(configUrls.getMaterialDetail, {
					id: that.materialId
				}).then(res => {
					if (res.code == "10000") {
						const respData = res.data.result;
						that.productInfo = respData.productInfo;
						that.videoTitles = respData.graphic.videoTitles;
						that.lines = respData.graphic.lines;
						that.elasticTitles = respData.graphic.elasticTitles;
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					} 
				}); 
			},
			getOriginalClassification() {
				let that = this;
				this.$Request.postJson(configUrls.getOriginalClassification, {
					id: that.materialId,
				}).then(res => {
					if (res.code == "10000") {
						that.tabOriginalData = that.tabOriginalData.concat(res.data.result);
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					} 
				}); 
			},
			saveVideoClick(downLoadUrl) {//保存图片到相册按钮的点击事件函数
				let that = this
				uni.getSetting({
					success(res) {
						console.log(res);
						if (!res.authSetting['scope.writePhotosAlbum']) {
							uni.authorize({
							scope: 'scope.writePhotosAlbum',
							success(res) {
								that.downloadFileClick(downLoadUrl);
							},
							fail() {
								uni.showModal({
									content: '请允许相册权限, 拒绝将无法正常保存视频',
									showCancel: false,
									success() {
										uni.openSetting({
											success(settingdata) {
												if (settingdata.authSetting['scope.writePhotosAlbum']) {} else {
													console.log('获取权限失败')
													uni.showToast({
														title: "获取权限失败",
														icon: 'none',
														duration: 2000
													});
												}
											}
										})
									}
								})
							}
						})
						} else {
							that.downloadFileClick(downLoadUrl)
						}
					}
				})
			},
			downloadFileClick(url) {
				uni.showLoading({
					mask: true,
					title: '下载中...'
				})
				let that = this;
				let fileName = new Date().valueOf();
				const task = uni.downloadFile({
					url: url,
					filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.mp4', //  拼接本地文件路径
					success: (res) => {
						let filePath = res.filePath;
						uni.saveVideoToPhotosAlbum({
							filePath,
							success: (res) => {
								uni.showToast({
									title: '下载成功',
									icon: 'none',
									duration: 2000
								})
								let fileMgr = wx.getFileSystemManager();
								// 删除本地文件
								fileMgr.unlink({
									filePath: wx.env.USER_DATA_PATH + '/' + fileName +
										'.mp4',
									success: function(r) {
										console.log(r)
									},
								})
							},
							fail(err) {
								uni.showToast({
									title: '保存失败',
									icon: 'none',
									duration: 2000
								})
							},
							complete(res) {
								console.log(res)
								uni.hideLoading()
							}
						})
					},
					fail(err) {
						that.mescroll.resetUpScroll();
						uni.showToast({
							title: '下载失败,请稍后再试',
							icon: 'none',
						})
					},
					complete(res) {
						console.log(res)
					}
				})
				task.onProgressUpdate(this.onProgress)
			},
			onProgress(res) {
				uni.showLoading({
					mask: true,
					title: res.progress ? '下载中' + res.progress + "%" : '下载中...'
				})
			},
			clickMaterialTab(isFirstTab) {
				if (isFirstTab) {
					this.currentTab = 0;
				} else {
					this.currentTab = 1;
				}
			},
			clickTab(e) {
				let clickIndex = e.target.dataset.current;			//当前标签的索引
				let singleNavWidth = this.windowWidth / 5;  		//每个标签的宽度, 显示5个标签		
				this.scrollLeft = (clickIndex - 2) * singleNavWidth;//水平滚动条位置, tab选项居中 
				this.currentOriginalTab = clickIndex;
				this.chooseOriginalType = this.tabOriginalData[clickIndex].value;
				this.mescroll.resetUpScroll();
			},
			copyLinkUrl(url){
				uni.setClipboardData({
					data: url,
					success: function () {
					    uni.showToast({
					        title: "复制成功",
					        icon: 'none',
							duration: 2000
					    });
					}
				});
			},
		},
	}
</script>

<style>
	@import url("../../css/material/materialDetail.css");
</style>
